#include "player.h"
#include "../subsystems/input.h"

Player::Player(RenderData render_data)
	: Entity(render_data)
{}

inline void Player::move(int x, int y, int& camera_x, int& camera_y, int window_w, int window_h)
{
	Sprite& s = multi_sprite.selected();
	pos.x += x;
	pos.y += y;
	camera_x = pos.x - window_w / 2 + pos.w / 2;
	camera_y = pos.y - window_h / 2 + pos.h / 2;
	render_data.dst.x = window_w / 2 - s.src.w / 2;
	render_data.dst.y = window_h / 2 - s.src.h / 2;
	render_data.dst.w = s.src.w;
	render_data.dst.h = s.src.h;
}

void Player::update(State &state, bool pressed_keys[], int& camera_x, int& camera_y)
{
	int x = 0, y = 0;
	y -= pressed_keys[Input::KEY_w] ? 10 : 0;
	x -= pressed_keys[Input::KEY_a] ? 10 : 0;
	y += pressed_keys[Input::KEY_s] ? 10 : 0;
	x += pressed_keys[Input::KEY_d] ? 10 : 0;
	moved_x = x;
	moved_y = y;
	move(x, y, camera_x, camera_y, state.window_w, state.window_h);

	if (pressed_keys[Input::KEY_a] && !pressed_keys[Input::KEY_d])
		multi_sprite.selected_sprite = RUNNING_LEFT;
	else if (pressed_keys[Input::KEY_d] && !pressed_keys[Input::KEY_a])
		multi_sprite.selected_sprite = RUNNING_RIGHT;
	else if ((pressed_keys[Input::KEY_w] || pressed_keys[Input::KEY_s]) && !(pressed_keys[Input::KEY_w] && pressed_keys[Input::KEY_s])) {
		if (multi_sprite.selected_sprite == IDLE_LEFT)
			multi_sprite.selected_sprite = RUNNING_LEFT;
		if (multi_sprite.selected_sprite == IDLE_RIGHT)
			multi_sprite.selected_sprite = RUNNING_RIGHT;
	} else {
		multi_sprite.sprites[multi_sprite.selected_sprite].current_frame = 0;
		if (multi_sprite.selected_sprite == RUNNING_LEFT)
			multi_sprite.selected_sprite = IDLE_LEFT;
		if (multi_sprite.selected_sprite == RUNNING_RIGHT)
			multi_sprite.selected_sprite = IDLE_RIGHT;
	}
}

void Player::render(SDL_Renderer *renderer)
{
	Drawable::render(renderer);
}

void Player::undo(State &state, bool pressed_keys[], int& camera_x, int& camera_y)
{
	move(-moved_x, -moved_y, camera_x, camera_y, state.window_w, state.window_h);
}